<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-10-14
 * Time: 下午8:45
 */

namespace Admin\Controller;
use Common\Controller\AdminCommonController;
use Think\Auth;

class RoleController extends AdminCommonController {
    protected $_model;

    function _initialize(){
        parent::_initialize();
        $this->_model = D('Admin/AuthGroup');
    }

    /*
     * 角色列表
     * */
    public function index(){
        $list = $this->_model->getList();
        $this->assign($list);
        $this->display();
    }

    /**
     * 角色添加
     */
    public function edit(){
        $roleid = I("get.id",0,'intval');
        if($roleid){
            $info = $this->_model->detail($roleid);
            $this->assign("role",$info);
        }
        $this->display();
    }

    /*
     * 角色信息添加与修改
     * */
    public function update(){
        if(IS_POST){
            $id = I('post.id');
            $title = I('post.title');
            $status = I('post.status');

            empty($title) && $this->returnData('角色名称不能为空！');
            if(abslength($title) > 30){
                $this->returnData('角色名称长度不能超过30个字符！');
            }

            $data = array();
            $data['title'] = $title;
            $data['status'] = $status;

            $where = array();
            $where['title'] = $title;
            if($id){
                $where['id'] = array('neq',$id);
                $msg = '修改';
                $data['id'] = $id;
            }else{
                $msg = '添加';
            }
            if($this->_model->where($where)->getField('id')){
                $this->returnData('该角色名称已存在！');
            }

            $data['rules'] = '';
            if($this->_model->update($data,$id)){
                unset($data);
                $this->returnData($msg.'成功！',1,U('Role/index'));
            }else{
                $this->returnData($msg.'失败！');
            }
        }else{
            $this->returnData('请求方式错误！');
        }
    }

    /*
     * 删除角色，同时删除权限表数据，和角色用户关系表数据
     * */
    public function del(){
        if(IS_GET){
            $id = I("get.id",0,'trim');
            empty($id) && $this->returnData('请选择操作项！');

            M()->startTrans();

            $where = array();
            $where['id'] = $id;
            $result = $this->_model->delete($id);

            unset($where['id']);
            $where['group_id'] = $id;
            $result_two = $this->_model->deleteAccess($id);

            if($result && $result_two >= 0){
                M()->commit();
                $this->returnData('删除成功！',1);
            }else{
                M()->rollback();
                $this->returnData('删除失败！');
            }
        }else{
            $this->returnData('请求方式错误！');
        }
    }

    /*
     * 禁用或启用角色
     * */
    public function setStatus(){
        if(IS_GET){
            $id = I('get.id');
            empty($id) && $this->returnData('请选择操作项！');

            $where = array();
            $where['id'] = $id;
            $status = $this->_model->where($where)->getField('status');
            $status = $status == 1 ? 0 : 1;

            if($this->_model->where($where)->setField('status',$status)){
                unset($where);
                $this->returnData('操作成功！',1);
            }else{
                $this->returnData('操作失败！');
            }
        }else{
            $this->returnData('请求方式错误！');
        }
    }

    /*
     * 获取此角色用户列表
     * */
    public function user_list(){
        if(IS_GET){
            $id = I('get.id');
            empty($id) && $this->returnData('请选择操作项！');

            $where = array();
            $where['a.group_id'] = $id;
            $where['a.uid'] = array('neq',C('MANAGE_id'));

            //获取该角色下的用户ID
            $rules_user = $this->_model->getRoleUserId($where);

            //获取系统所有管理员
            $user = $this->_model->getUser();

            $this->assign('list',$user);
            $this->assign('rules_user',$rules_user);
            $this->assign('roleid',$id);
        }else{
            $this->returnData('请求方式错误！');
        }
        $this->display();
    }

    /**
     * 添加角色用户
     */
    public function addRoleUser(){
        if(IS_POST){
            $roleid=I("post.roleid");//角色ID
            $uid = I('post.uid');//选中的用户

            empty($roleid) && $this->returnData('请选择操作项！');
            empty($uid) && $this->returnData('请选择用户！');

            $manageArr = !is_array($uid) ? str2arr($uid) : $uid;

            M()->startTrans();
            //删除当前角色的所有用户权限记录
            $result = $this->_model->deleteAccess($roleid);
            if($result<0){
                M()->rollback();
                $this->returnData('修改用户权限失败！');
            }

            //插入已选择用户的权限信息
            if(!empty($manageArr) && is_array($manageArr)){
                $data = array();
                $data['group_id'] = $roleid;

                foreach($manageArr as $val){
                    //判断用户是否在其他分组
                    if($this->_model->getTipField('auth_group_access',array('uid'=>$val),'uid')){
                        M()->rollback();
                        $manageName = $this->_model->getTipField('manage',array('id'=>$val),'account');
                        $this->returnData('【'.$manageName.'】'.'用户已存在其他角色里！');
                    }

                    $data['uid'] = $val;
                    $result = $this->_model->updateAccess($data,$roleid);

                    if(!$result){
                        M()->rollback();
                        $this->returnData('操作失败！');
                    }
                }
            }

            M()->commit();
            $this->returnData('操作成功！',1);

        }else{
            $this->returnData('请求方式错误！');
        }
    }

    //授权列表页面
    public function quan(){
        if(IS_GET){
            $id = I('get.id');
            empty($id) && $this->returnData('请选择操作项！');

            $this->auth = new Auth();
            $rules = $this->_model->where(array('id'=>$id))->getField('rules');
            $list = $this->auth->getRoleAuthList($this->manage_id);
            $html = $this->getQuanHtml($list,str2arr($rules));
            $this->assign('html',$html);
            $this->assign('id',$id);
        }else{
            $this->returnData('请求方式错误！');
        }

        $this->display();
    }

    /*
     * 授权操作
     * */
    public function updateQuan(){
        if(IS_POST){
            $id = I('post.id');//角色ID
            $rules_id = I('post.rules_id');//规则ID，多个由英文逗号隔开
            empty($id) && $this->returnData('请选择操作项！');
            empty($rules_id) && $this->returnData('请选择权限节点！');

            $data = array();
            $data['id'] = $id;
            $data['rules'] = $rules_id;

            if($this->_model->update($data,$id)){
                $this->clearCache($id);
                $this->returnData('授权成功！',1);
            }else{
                $this->returnData('授权失败！');
            }
        }else{
            $this->returnData('请求方式错误！');
        }
    }

    /*
     * 递归输出html
     * */
    private function getQuanHtml($list,$rules){
        $str = '<ul>';
        foreach($list as $value){
            if(in_array($value['id'],$rules)){
                $checked = 'checked="checked"';
            }
            $str .= '<li><p><label><input type="checkbox" name="permissions" '.$checked.' value="'.$value['id'].'">'.$value['title'].'</label></p>';
            $checked = '';
            if($value['child']){
                $str .= $this->getQuanHtml($value['child'],$rules);
            }
            $str .= '</li>';
        }
        $str .= '</ul>';
        return $str;
    }

    /**
     * 清除节点缓存
     */
    private function clearCache($id){
        S(C('DB_PREFIX').'_role_auth_list_'.$id,null);
    }
}